package com.demo.gateway.filter;

import java.net.URI;
import java.time.Instant;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;

import com.demo.gateway.util.UriUtil;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * @author: demo
 * @date: 2020年6月18日
 * @Document : 网关过滤器
 */
@Slf4j
@Service
public class GatewayGlobalFilter implements GlobalFilter {
	//TODO
	/**
	 * token 拦截... 
	 * 请求开关...
	 */
	
	private final static String GATEWAY_START_TIME = "GATEWAY_START_TIME";

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		exchange.getAttributes().put(GATEWAY_START_TIME, Instant.now().toEpochMilli());
		URI  uri=exchange.getRequest().getURI();
		return chain.filter(exchange).then(Mono.fromRunnable(() -> {
			long startTime = exchange.getAttribute(GATEWAY_START_TIME);
			long endTime = (Instant.now().toEpochMilli() - startTime);
			log.info("请求==>{}{} ,转发时间==>{} ms",UriUtil.getUriAddress(uri),uri.getPath(), endTime);
		}));
	}

}
